/*******************************************************************************
 * Copyright (c) 2008 Sylvain Sicard.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Sylvain Sicard - initial API and implementation
 ******************************************************************************/
package fr.jade.service.fm.deployment;

import org.objectweb.fractal.api.Component;
import org.objectweb.fractal.api.NoSuchInterfaceException;
import org.objectweb.fractal.api.factory.GenericFactory;
import org.objectweb.fractal.api.factory.InstantiationException;
import org.objectweb.fractal.api.type.ComponentType;

import fr.jade.base.JadeBaseObject;
import fr.jade.util.FractalUtil;

public class FractalComponentTask extends JadeBaseObject implements DeploymentTask, NewComponentTask {
  
  protected GenericFactory gf;
  protected ComponentType type;
  protected String controllerDesc;
  protected String contentDesc;
  protected String name;
  
  protected Component cmp;
  
  public FractalComponentTask(GenericFactory gf, ComponentType type, String controllerDesc, String contentDesc, String name){
    assert gf != null          : "GenericFactory cannot be null";
    assert type != null        : "Type cannot be null";
    assert controllerDesc != null  : "controllerDesc cannot be null";
    assert !controllerDesc.equals("") : "controllerDesc cannot be empty";
    //contentDesc could be null
    
    this.gf=gf;
    this.type=type;
    this.controllerDesc=controllerDesc;
    this.contentDesc=contentDesc;
    this.name=name;
    this.cmp=null;
  }

  public void execute() throws DeploymentException{
    log("execute :" +toString());
    try {
      // Fix bug in ReflexGenericFactory
      //gf = (GenericFactory) Reflex.getOptDualInterface((Interface)gf);
      cmp = (Component)gf.newFcInstance(type, controllerDesc, contentDesc);
      FractalUtil.getNameController(cmp).setFcName(name);
    } catch (InstantiationException e) {
      throw new DeploymentException("Exception during " + name + " instanciation", e);
    } catch (NoSuchInterfaceException e) {
      throw new DeploymentException("Exception during " + name + " instanciation", e);
    }
  }

  public Component getComponent()throws DeploymentException{
    if(cmp==null) throw new DeploymentException("Workflow error");
    return cmp;
  }
  
  public String getLevelName(){
    return "newComponent";
  }
  
  public String toString(){
    return 
    "FractalComponentTask["+
    "gf:"+ gf + " - "+
    "type:" + type + " - " +
    "controllerDesc:" + controllerDesc + " - " +
    "contentDesc:" + contentDesc + " - " + 
    "name:" + name + "]";
  }
}
